﻿using Ec.NETCoreFramework.Common;
using Ec.NETCoreFramework.Common.Core.Helpers;
using Ec.NETCoreFramework.Common.MQ;
using Ec.NETCoreFramework.Common.Core;
using Quartz;
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Ec.NETCoreFramework.Common.Plug.Core;

namespace Job_WechatMoment
{
    [PersistJobDataAfterExecution] //下一次执行可以本次的结果
    [DisallowConcurrentExecution] //不让任务在同一段时间内执行
    public class Moment : JobBase, IJob
    {
        private static AppConfig _appConfig;
        private static JobConfig _jobConfig;
        public override JobDto InitJobModel()
        {
            var v = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            if (string.IsNullOrEmpty(v))
            {
                v = "Production";
            }
            Console.WriteLine("ASPNETCORE_ENVIRONMENT" + v);
            _appConfig = (new ConfigHelper().Get<AppConfig>("appconfig", v) ?? new AppConfig());

            _jobConfig = _appConfig.GetJob("WechatMoment");
            if (_jobConfig == null|| _jobConfig.CronSchedule==null) return null;
            return new JobDto("moment", "wechat", "微信群发发送定时任务", _jobConfig.CronSchedule, new Hashtable() { { "token", "" } });
        }
        public Task Execute(IJobExecutionContext context)
        {
            Console.WriteLine("**************"+DateTime.Now+"定时器开始触发**********************");
            var ht = context.JobDetail.JobDataMap.Get("data") as Hashtable;

            return Task.Run(() =>
            {
                var msgPublish = new MsgPublish(_appConfig.MQConf.Server, _appConfig.MQConf.UserName, _appConfig.MQConf.Pwd, "wechat");
                foreach (var item in _jobConfig.Consumes)
                {
                    var text = item.Domain;
                    Console.WriteLine("================" + item.MQName + text + " * *****************");
                    msgPublish.Publish("wechat-" + item.MQName, Encoding.UTF8.GetBytes(text));
                    
                }

            }
            );
            //return Task.CompletedTask;
        }
    }
}
